Oversold RSI with Tight Stop-Loss Strategy (by Coinrule)KRAKEN:LINKUSD
This is one of the best strategies that can be used to get familiar with technical indicators and start to include them in your rules on Coinrule .
ENTRY
1. This trading system uses the RSI (Relative Strength Index) to anticipate good points to enter positions. RSI is a technical indicator frequently used in trading. It works by measuring the speed and change of price movements to determine whether a coin is oversold (indicating a good entry point) or overbought (indicating a point of exit/entry for a short position). The RSI oscillates between 0 and 100 and is traditionally considered overbought when over 70 and oversold when below 30.
2. To pick the right moment to buy, the strategy enters a trade when the RSI falls below 30 indicating the coin is oversold and primed for a trend reversal.
EXIT
The strategy then exits the position when the price appreciates 7% from the point of entry. The position also maintains a tight stop-loss and closes the position if the price depreciates 1% from the entry price. The idea behind this is to cut your losing trades fast and let your winners ride.
The best time frame for this strategy based on our back testing data is the daily. Shorter time frames can also work well on certain coins, however in our experience, the daily works best. Feel free to experiment with this script and test it on a variety of your coins! With our back testing data a trading fee of 0.1% is taken into account. The fee is aligned to the base fee applied on Binance, which is the largest cryptocurrency exchange by volume. In the example shown, this strategy made a handsome net profit of 52.6% on Chainlink with 66.67% of trades being profitable.
You can execute this strategy on your favorite exchanges with Coinrule .
Cari dalam skrip untuk "stop loss"
isamuch - 2MA Cross and Stop Lossสัญญาณซื้อ/ขาย : มาจาก Moving Average สองเส้นตัดกัน
Stop Loss : มาจากราคาต่ำสุด/สูงสุดของช่วงระหว่าง Moving Average สองเส้นตัดกันก่อนหน้ากับ Moving Average ตัดกันปัจจุบัน
Parabolic SAR Strategy With take profit and stop lossDo not make it too difficult!
This is my first strategy! I took the Parabolic SAR Strategy and added Stop Loss and Take profit, and I can see some fantastic results in 2h-3h-4h on some of the Crypto coins.
This is for training only, and I do not recommend using it as part of a trading bot, however, I do myself.
MultiPrice AlertThis is an alert script using Pinescript version 4. This enables one to set 5 alerts (1 StopLoss, 4 Targets), on 3 different symbols, at using a single alert in the UI.
Every visible line will only appear on the symbols that are selected. After setting targets when making an alert, select this indicator as a condition. Change the name to whatever you want, usually the names of the set of tickers.
The Alert message is dyanmic showing which Symbol with each type of alert, at whatever price.
Ability to disable the targets + symbols.
Alerts work by Stop Loss crossing under price and Targets Cross Over. Enabling the "Short" Targets reverses this.
The line that is being displayed is actually the price of the asset being moved over x number of bars. I have not found a way to plot a traditional horizontal line, as the code for it uses a fixed price.
As it being a user input, it is a variable. Any help with this would be appreicated.
Alerts are set to once per bar.
Known bug that sometimes if the prices that you set are inside the current candle stick, then your alert will immeaditally fire, either change the timeframe or let it fire and wait fo
After a target is hit, I reccomend setting the alert to 0 and REMAKING the alert. You MUST REMAKE THE ALERT AFTER ANY CHANGES. This script WILL NOT CHANGE ALERTS AS YOU CHANGE SETTINGS.
TradingView Alerts are not this smart , at least I haven't found a way to do this yet.
Anti-Volume Stop Loss multi timeframe [LM]Hello Traders,
I would like to introduce you fork of popular indicator Anti-Volume Stop Loss created by Buff Dormeier and cracked here on tradingview by @Rafka so shout out to him. I have tried to crack it myself as well as I'm big fan of Dormeier's work but it's not easy so really big thanks to Rafka
I have refactored original script and have included multi timeframe setting.
As its shown below you can select higher timeframe to track lower one:
Enjoy!
Bitlinc MARSI Study AST w/ Take Profit & Stop loss - beta 0.1This script is beta 0.1 - will update as soon as the script is tradable
This script is based on AST on a 10 minute timeframe. You can change the asset and the timeframe for any asset you want to trade, but for it to work correct ALL settings have to be testes in the Strategy section of the TradingView. Each assets and timeframe require a different mixture of settings. This is NOT a one settings fits all trading for all assets on any timeframe. Below are the settings and explanation on how it works.
How it fires a buy / sell:
The script will plot an RSI with upper and lower bands in a separate indicator window. The idea behind this script is to fire a LONG when MA crosses OVER lower band and fire a SHORT when the MA crosses under the lower band. Each order that fires is an OCO (Order Cancels Order) for pyramiding.
Settings:
You have full control of these settings as mentioned above, you must configure every part of this script for each asset and timeframe you trade.
- Length of MA
- Length
- Upper bands of RSI
- Lower bands of RSI
- Take profit percentage
- Stop loss percentage
- Month to start and end the strategy (within 2020)
- Day to start and end the strategy (within 2020)
- Quantity type
- Slippage
- Pyramiding
***Remember that after the signal to enter or exit a trade is fired, the alert will trigger AFTER the close of the candle that caused the tigger to fire
ATR Stop Loss LONG/SHORT by melihgulerYou can monitor the stop loss level according to ATR in 2 ways (Long/Short).
RSI + EMA+ MTF Stop-LossThis is a simple RSI with multiple MTF (No security) to help with direction short and long-term.
The rsi for the current chart has a noise reduction, while the rest are based on ma's.
I have supplied an extra flexible mtf rsi ma for potential adjustable/long-term stop-loss or direction identification.
Enjoy
RSI Stop LossExperiment for using RSI as a stop loss value, shows where the price will be when the RSI increases or decreases by a specified amount.
poki buy and sell Take profit and stop lossThis indicator is based on modelius model of lazy bear weis model with ATR for the buy=B sell =S
in addition there is Take profit and stop loss in % both for short and for long
next stage is to know the resistance level and support based on bollinger marked in blue and red dots
Also included Parabolic Sar (blue and red dots rising up or down)
The color of bulish or bearish zone is based on the cross of Hull avreage and linear regression ( for each time set may need different setting for accuracy )
So how to use this scrupt to better profit
1. if you have B signal and its on lower support level then its good starting place for buy. look at the Parabolic Sar if its in agreement. The exit can be either by S =sell, Take profit that you decide on % or by end of Parabolic SAR upward
2. exact the oposite for short
Play with setting for the desired results or change modify this script for your purpose
Pivot Stop LossHere we intend to use pivot points for stop loss and take profit. This has the added benefit of helping you to visualize support and resistance levels.
Hull modelius take profit and stop lossThis model has Hull moving average, fibs in form of Bollinger ,SMA and Modelius model with ATR for buy and sell power based on weis volume. Inside alerts for buy and sell. take profit and stop loss for both longs and shorts
so have fun
SL + TP Dynamics - By M.LolasStop Loss e Take Profit dinâmicos para operações semiautomatizadas.
By M.Lolas
STOP-LOSS-RSI with Edge-Preserving Filter Strategy V2Modified RSI strategy with entry and exit points.
I have allowed for High and Low risk for anyone interested in using it (NO GUARANTEES. DO YOUR OWN RESEARCH).
I will later consider incorporating the standard RSI for exit points. I am sure returns will increase based on current test runs :)
Returns look good based on the strategy result.
Smart Money Swing Strategy [All-in-One]# Pro Swing Trader 📈
A comprehensive swing trading indicator for TradingView that combines multiple confluence factors to identify high-probability trade setups with built-in risk management.
## 🎯 Overview
This indicator is designed for swing traders who want to catch momentum pullbacks with precision entries. It filters trades using multiple timeframe analysis, RSI zones, volume confirmation, and EMA trends to deliver only the highest-confidence setups.
### Key Features
✅ **Multi-Timeframe Confluence** - Confirms trades with higher timeframe analysis (Daily, 4H, etc.)
✅ **Smart Entry Signals** - Detects pullback-to-EMA reclaim patterns
✅ **Automatic Risk Management** - Calculates stops, targets, and R-multiples
✅ **Dynamic Stop Loss** - ATR trailing stop + break-even automation
✅ **Real-Time HUD Dashboard** - Live confluence scoring and trade metrics
✅ **Comprehensive Alerts** - Entry, TP1, TP2, and stop-loss notifications
✅ **Visual Trade Levels** - Clear on-chart stop-loss and take-profit lines
---
## 📊 How It Works
### Signal Logic
The indicator identifies two types of signals:
**Base Signals** (Small triangles):
- Price pulls back between Fast EMA and Slow EMA
- RSI is in the swing zone (40-60 by default)
- Price reclaims the Fast EMA with momentum
- Optional: Volume spike confirmation
**High-Confidence Signals** (Large triangles):
- All base signal criteria met
- Higher timeframe confirms the trend direction
- HTF RSI and slope alignment
- These are your primary trade signals
### Entry Conditions
#### Long Entry (🟢 HC L)
1. Fast EMA > Slow EMA (uptrend)
2. Previous candle closed between the EMAs (pullback)
3. Current candle crosses above and closes above Fast EMA (reclaim)
4. RSI between 40-60 (swing zone)
5. **HTF Confirmation**: Daily/4H price above EMA50, RSI > 50, positive slope
6. Optional: Volume > 1.5x 20-bar average
#### Short Entry (🔻 HC S)
1. Fast EMA < Slow EMA (downtrend)
2. Previous candle closed between the EMAs (pullback)
3. Current candle crosses below and closes below Fast EMA (reclaim)
4. RSI between 40-60 (swing zone)
5. **HTF Confirmation**: Daily/4H price below EMA50, RSI < 50, negative slope
6. Optional: Volume > 1.5x 20-bar average
---
## 🎛️ Settings & Parameters
### Trend Parameters
- **Fast EMA**: Default 20 - Quick trend detection
- **Slow EMA**: Default 50 - Major trend filter
- **Swing Lookback**: Default 10 - Bars to find swing high/low for stops
### RSI Settings
- **RSI Length**: Default 14
- **RSI Min**: Default 40 - Lower bound of swing zone
- **RSI Max**: Default 60 - Upper bound of swing zone
### Risk Management
- **Final TP Risk-Reward (R)**: Default 2.0 - Main profit target multiplier
- **TP1 R Multiple**: Default 1.0 - Partial profit target
- **Use Break-even Stop**: Move stop to entry after 1R profit
- **ATR Trailing Stop**: Dynamic stop based on ATR(14) x 2.0
### Filters
- **Require Volume Spike**: Optional volume confirmation filter
- **Use Higher TF Confirmation**: Enable multi-timeframe analysis
- **Higher TF**: Default "D" (Daily) - Can use 240 (4H), W (Weekly), etc.
---
## 📈 Dashboard (HUD)
The top-center dashboard shows real-time confluence status:
| Column | Meaning |
|--------|---------|
| **Trend** | Current trend direction (UP/DOWN/Flat) |
| **HTF** | Higher timeframe alignment (Bull/Bear/Flat) |
| **RSI Zone** | Is RSI in swing zone? (YES/NO) |
| **Volume** | Volume spike detected? (YES/NO) |
| **Signal** | Active signal type (HC LONG/HC SHORT/None) |
| **R Risk** | Current profit in R-multiples |
| **Stop** | Current stop-loss level |
| **TP1** | Partial take-profit status |
| **TP2** | Final take-profit status |
| **Conf %** | Overall confluence score (0-100%) |
### Confidence Score Breakdown
- **20%** - Trend present (up or down)
- **30%** - HTF confirmation aligned (or 15% if HTF off)
- **20%** - RSI in swing zone
- **10%** - Volume spike
- **20%** - High-confidence signal triggered
**Scoring**:
- 🟢 70%+ = High probability setup
- 🟡 40-69% = Moderate setup
- 🔴 <40% = Low probability
---
## 🔔 Alert Setup
The indicator includes 8 alert conditions:
### Entry Alerts
- **HC LONG ENTRY** - High-confidence long signal triggered
- **HC SHORT ENTRY** - High-confidence short signal triggered
### Profit Target Alerts
- **LONG TP1 Reached** - Hit partial profit (1R by default)
- **LONG Final TP Reached** - Hit final target (2R by default)
- **SHORT TP1 Reached** - Hit partial profit
- **SHORT Final TP Reached** - Hit final target
### Stop Loss Alerts
- **LONG Stop/BE/Trail Level Hit** - Long position stopped out
- **SHORT Stop/BE/Trail Level Hit** - Short position stopped out
### How to Set Up Alerts
1. Click "Add Alert" on TradingView
2. Choose this indicator from the dropdown
3. Select desired alert condition
4. Set alert to trigger "Once Per Bar Close"
5. Customize notification method (popup/email/webhook)
---
## 📋 Trading Workflow
### 1. Wait for High-Confidence Signal
Look for the large **HC L** or **HC S** triangle on chart close.
### 2. Verify Confluence
Check the HUD dashboard:
- Confidence score should be 70%+
- HTF status should show alignment
- RSI Zone should be "YES"
### 3. Entry
Enter the trade at market or on next candle open.
### 4. Set Stop Loss
Use the **initial stop** shown in the HUD (red line on chart):
- **Longs**: Below the swing low (10-bar lookback)
- **Shorts**: Above the swing high (10-bar lookback)
### 5. Set Take Profits
- **TP1**: 1R (50% position close) - Yellow line
- **TP2**: 2R (remaining 50% close) - Green line
### 6. Manage the Trade
- Monitor the **R Risk** column to track profit
- Stop moves to break-even automatically after 1R (if enabled)
- ATR trailing stop engages dynamically (red line adjusts)
- Exit if price hits dynamic stop level
---
## 🎨 Visual Guide
### On-Chart Elements
**Triangles**:
- Small lime/red triangles = Base signals (lower confidence)
- Large lime/red triangles = High-confidence signals (trade these!)
**Lines**:
- 🟢 Green line = Fast EMA (20)
- 🟠 Orange line = Slow EMA (50)
- 🔴 Red line = Dynamic stop-loss level
- 🟡 Yellow line = TP1 level
- 🟢 Green line = TP2 (final target)
**HUD Colors**:
- 🟢 Green = Bullish/Active/Good
- 🔴 Red = Bearish/Inactive/Warning
- 🟡 Yellow = Neutral/Caution
- 🔵 Blue = Informational
- ⚫ Gray = Disabled/Off
---
## 💡 Strategy Tips
### Best Practices
1. **Only trade High-Confidence signals** - Ignore base signals unless very experienced
2. **Respect the HTF** - Don't fight the higher timeframe trend
3. **Use proper position sizing** - Risk 1-2% of account per trade
4. **Partial profits work** - Take 50% off at TP1, let rest run to TP2
5. **Let winners run** - Trailing stop helps capture extended moves
6. **Be patient** - Quality over quantity; wait for 70%+ confluence
### Optimal Timeframes
- **Primary Chart**: 1H, 4H, Daily (swing trading)
- **HTF Setting**: One level higher than your chart
- If trading 1H → Set HTF to 4H or D
- If trading 4H → Set HTF to D or W
- If trading Daily → Set HTF to W
### Market Conditions
**Best Performance**:
- Trending markets with healthy pullbacks
- Clear support/resistance zones
- Moderate volatility
**Avoid Trading**:
- Extremely choppy/sideways markets
- Major news events (unless experienced)
- Low confidence scores (<40%)
---
## ⚙️ Advanced Customization
### Aggressive Setup (More Signals)
```
Fast EMA: 12
Slow EMA: 26
RSI Min: 35
RSI Max: 65
Use HTF Confirmation: OFF
Require Volume Spike: OFF
```
### Conservative Setup (Fewer, Higher Quality)
```
Fast EMA: 20
Slow EMA: 50
RSI Min: 45
RSI Max: 55
Use HTF Confirmation: ON
Require Volume Spike: ON
Final TP R: 3.0
```
### Scalping Adaptation (Not Recommended)
```
Fast EMA: 9
Slow EMA: 21
Swing Lookback: 5
TP1 R: 0.5
Final TP R: 1.0
```
---
## ⚠️ Risk Disclaimer
**IMPORTANT**: This indicator is for educational and informational purposes only.
- Past performance does not guarantee future results
- No indicator is 100% accurate
- Always use proper risk management
- Never risk more than you can afford to lose
- Consider using a demo account first
- Seek professional financial advice if needed
Trading involves substantial risk of loss and is not suitable for all investors.
---
## 🔧 Troubleshooting
### "No signals appearing"
- Check if HTF confirmation is enabled but market isn't aligned
- Verify RSI zone isn't too restrictive
- Ensure volume spike isn't filtering out all setups
- Try adjusting EMA lengths for your asset
### "Too many false signals"
- Enable HTF confirmation
- Tighten RSI zone (e.g., 45-55)
- Enable volume spike requirement
- Only trade 70%+ confidence setups
### "Stops too tight/wide"
- Adjust Swing Lookback length
- Modify ATR multiplier for trailing stop
- Consider the asset's volatility
### "Alerts not working"
- Ensure alert is set to "Once Per Bar Close"
- Check indicator is added to the chart
- Verify TradingView notification settings
---
## 📚 Version History
**v1.0 (Current)**
- Initial release
- Multi-timeframe confluence system
- Dynamic risk management
- Real-time HUD dashboard
- Comprehensive alert system
- ATR trailing stops
- Break-even automation
---
## 🤝 Support & Feedback
If you find this indicator helpful:
- ⭐ Star the script on TradingView
- 💬 Share your results and feedback
- 🐛 Report bugs or suggest improvements
- 📖 Share with other traders
---
## 📖 Additional Resources
### Recommended Reading
- "The New Trading for a Living" by Dr. Alexander Elder
- "Swing Trading Using Multiple Timeframes" - Educational articles
- Risk management and position sizing guides
### Learn More About
- Multiple timeframe analysis
- EMA crossover strategies
- RSI divergence and zones
- ATR-based stops
- R-multiple profit management
---
## 📝 License
This indicator is provided as-is for personal trading use.
**Usage Rights**:
- ✅ Use for personal trading
- ✅ Modify for personal use
- ❌ Resell or redistribute
- ❌ Claim as original work
---
## 🎓 Quick Start Checklist
- Add indicator to TradingView chart
- Set your preferred timeframe (1H/4H/Daily)
- Configure HTF setting (one level higher)
- Review default parameters
- Set up entry alerts (HC LONG/SHORT)
- Set up TP and SL alerts
- Test on historical data
- Paper trade first
- Start with small position sizes
- Track your results
---
**Happy Trading! 📊💰**
*Remember: Discipline, patience, and risk management are the keys to long-term success.*
"Clean Market Structure & Trend Confirmation" TP LADDER(UPDATED)Clean Market Structure & Trend Confirmation — TP Ladder
This indicator is designed to identify high-probability intraday trend trades using market structure, momentum confirmation, and a visual ribbon system, with automatic take-profit and stop-loss levels plotted after confirmed signals.
WHAT THIS INDICATOR IS FOR
This script is built for active intraday traders trading SPY, QQQ, It focuses on trend continuation and directional momentum rather than scalping chop. It works best during regular market hours with extended hours enabled.
HOW TO LOAD (IMPORTANT)
Add the script to your chart
Set chart timeframe to 5-minute
Turn Extended Trading Hours ON
Use during the NY session (especially open and trend periods)
THE RIBBON (MOST IMPORTANT RULE)
The ribbon defines the trend.
• Blue/Teal ribbon = bullish trend
• Red ribbon = bearish trend
• Gray ribbon = compression / no trade zone
Only trade in the direction of the ribbon.
No ribbon alignment = no trade.
BULL & BEAR DOTS
“BULL” dot appears when structure flips bullish.
“BEAR” dot appears when structure flips bearish.
These confirm trend direction, not entries by themselves.
BUY & SELL ARROWS (ENTRIES)
• BUY arrow prints only when bullish ribbon, structure, momentum, and filters align
• SELL arrow prints only when bearish ribbon, structure, momentum, and filters align
• Arrows are non-repainting when using close-confirmed mode
No arrow = no trade.
CONTINUATION (C) LOGIC
The script allows limited continuation entries after pullbacks when structure realigns.
By default, only one continuation per direction per day is allowed to prevent overtrading and signal spam.
TAKE-PROFIT (TP) LADDER
When a BUY or SELL arrow confirms, the script automatically plots:
• TP1 = partial profit
• TP2 = extended target
• TP3 = final extension
• STOP = ATR-based stop loss
All levels are calculated using ATR and adjust automatically to volatility.
The ladder only appears after a confirmed signal.
HOW TO TRADE IT (SIMPLE FLOW)
Identify ribbon direction
Wait for BUY or SELL arrow
Enter on confirmation
Scale out at TP1, TP2, TP3
Respect the STOP line
If structure breaks or ribbon flips, exit.
WHAT TO AVOID
• Do not trade against the ribbon
• Do not trade in gray ribbon conditions
• Do not chase candles without arrows
• Do not expect constant signals (quality over quantity)
Tailwind.(BTC)Imagine the price of Bitcoin is like a person climbing a staircase.
The Steps (Grid): Instead of watching every single price movement, the strategy divides the market into fixed steps. In your configuration, each step measures **3,000 points**. (Examples: 60,000, 63,000, 66,000...).
The Signal: We buy only when the price climbs a full step decisively.
The "Expensive Price" Filter: If the price jumps the step but lands too far away (the candle closes too high), we do not buy. It is like trying to board a train that has already started moving too fast; the risk is too high.
Rigid Exits: The Take Profit (TP) and Stop Loss (SL) are calculated from the edge of the step, not from the specific price where you managed to buy. This preserves the geometric structure of the market.
The Code Logic (Step-by-Step)
A. The Math of the Grid (`math.floor`)
pinescript
level_base = math.floor(close / step_size) * step_size
This is the most important line.
What does it do? It rounds the price down to the nearest multiple of 3,000.
Example: If BTC is at 64,500 and the step size is 3,000:
1. Divide: $64,500 / 3,000 = 21.5$
2. `math.floor` (Floor): Removes the decimals $\rightarrow$ remains $21$.
3. Multiply: $21 * 3,000 = 63,000$.
Result: The code knows that the current "floor" is **63,000**, regardless of whether the price is at 63,001 or 65,999.
B. The Strict Breakout (`strict_cross`)
pinescript
strict_cross = (open < level_base) and (close > level_base)
Most strategies only check if `close > level`. We do things slightly differently:
`open < level_base`: Requires the candle to have "born" *below* the line (e.g., opened at 62,900).
`close > level_base`: Requires the candle to have *finished* above the line (e.g., closed at 63,200).
Why? This avoids entering on gaps (price jumps where the market opens already very high) and confirms that there was real buying power crossing the line.
C. The "Expensive Price" Filter (`max_dist_pct`)
pinescript
limit_price_entry = level_base + (step_size * (max_dist_pct / 100.0))
price_is_valid = close <= limit_price_entry
Here you apply the percentage rule:
-If the level is 63,000 and the next is 66,000 (a difference of 3,000).
-If `max_dist_pct` is **60%**, the limit is $63,000 + (60\% \text{ of } 3,000) = 64,800$.
-If the breakout candle closes at **65,000**, the variable `price_is_valid` will be **false** and it will not enter the trade. This avoids buying at the ceiling.
D. TP and SL Calculation (Anchored to the Level)
pinescript
take_profit = level_base + (step_size * tp_mult)
stop_loss = level_base - (step_size * sl_mult)
Note that we use `level_base` and not `close`.
-If you entered because the price broke 63,000, your SL is calculated starting from 63,000.
-If your SL is 1.0x, your stop will be exactly at 60,000.
This is crucial: If you bought "expensive" (e.g., at 63,500), your real stop is wider (3,500 points) than if you bought cheap (63,100). Because you filter out expensive entries, you protect your Risk/Reward ratio.
E. Visual Management (`var line`)
The code uses `var` variables to remember the TP and SL lines and the `line.set_x2` function to stretch them to the right while the operation remains open, providing that visual reference on the chart until the trade ends.
Workflow Summary
Strategy Parameters:
Total Capital: $20,000
We will use 10% of total capital per trade.
Commissions: 0.1% per trade.
TP: 1.4
SL: 1
Step Size (Grid): 3,000
We use the 200 EMA as a trend filter.
Feel free to experiment with the parameters to your liking. Cheers.
just takesi TimeMNO_2Step_Strategy_MOU_KAKU (Publish-Clear)//@version=5
strategy("MNO_2Step_Strategy_MOU_KAKU (Publish-Clear)", overlay=true, pyramiding=0,
max_labels_count=500, max_lines_count=500,
initial_capital=100000,
default_qty_type=strategy.percent_of_equity, default_qty_value=10)
// =========================
// Inputs
// =========================
emaSLen = input.int(5, "EMA Short (5)")
emaMLen = input.int(13, "EMA Mid (13)")
emaLLen = input.int(26, "EMA Long (26)")
macdFast = input.int(12, "MACD Fast")
macdSlow = input.int(26, "MACD Slow")
macdSignal = input.int(9, "MACD Signal")
macdZeroTh = input.float(0.2, "MOU: MACD near-zero threshold", step=0.05)
volLookback = input.int(5, "Volume MA days", minval=1)
volMinRatio = input.float(1.3, "MOU: Volume ratio min", step=0.1)
volStrong = input.float(1.5, "Strong volume ratio (Breakout/KAKU)", step=0.1)
volMaxRatio = input.float(3.0, "Volume ratio max (filter)", step=0.1)
wickBodyMult = input.float(2.0, "Pinbar: lowerWick >= body*x", step=0.1)
pivotLen = input.int(20, "Resistance lookback", minval=5)
pullMinPct = input.float(5.0, "Pullback min (%)", step=0.1)
pullMaxPct = input.float(15.0, "Pullback max (%)", step=0.1)
breakLookbackBars = input.int(5, "Pullback route: valid bars after break", minval=1)
// --- Breakout route (押し目なし初動ブレイク) ---
useBreakoutRoute = input.bool(true, "Enable MOU Breakout Route (no pullback)")
breakConfirmPct = input.float(0.3, "Break confirm: close > R*(1+%)", step=0.1)
bigBodyLookback = input.int(20, "Break candle body MA length", minval=5)
bigBodyMult = input.float(1.2, "Break candle: body >= MA*mult", step=0.1)
requireCloseNearHigh = input.bool(true, "Break candle: close near high")
closeNearHighPct = input.float(25.0, "Close near high threshold (% of range)", step=1.0)
allowMACDAboveZeroInstead = input.bool(true, "Breakout route: allow MACD GC above zero instead")
// 表示
showEMA = input.bool(true, "Plot EMAs")
showMouLabels = input.bool(true, "Show MOU/MOU-B labels")
showKakuLabels = input.bool(true, "Show KAKU labels")
showDebugTbl = input.bool(true, "Show debug table (last bar)")
showStatusLbl = input.bool(true, "Show status label (last bar always)")
locChoice = input.string("Below Bar", "Label location", options= )
lblLoc = locChoice == "Below Bar" ? location.belowbar : location.abovebar
// =========================
// 必ず決済が起きる設定(投稿クリア用)
// =========================
enableTPSL = input.bool(true, "Enable TP/SL")
tpPct = input.float(2.0, "Take Profit (%)", step=0.1, minval=0.1) // ←投稿クリア向けに近め
slPct = input.float(1.0, "Stop Loss (%)", step=0.1, minval=0.1) // ←投稿クリア向けに近め
maxHoldBars = input.int(30, "Max bars in trade (force close)", minval=1)
entryMode = input.string("MOU or KAKU", "Entry trigger", options= )
// ✅ 保険:トレード0件を避ける(投稿クリア用)
// 1回でもクローズトレードができたら自動で沈黙
publishAssist = input.bool(true, "Publish Assist (safety entry if 0 trades)")
// =========================
// EMA
// =========================
emaS = ta.ema(close, emaSLen)
emaM = ta.ema(close, emaMLen)
emaL = ta.ema(close, emaLLen)
plot(showEMA ? emaS : na, color=color.new(color.yellow, 0), title="EMA 5")
plot(showEMA ? emaM : na, color=color.new(color.blue, 0), title="EMA 13")
plot(showEMA ? emaL : na, color=color.new(color.orange, 0), title="EMA 26")
emaUpS = emaS > emaS
emaUpM = emaM > emaM
emaUpL = emaL > emaL
goldenOrder = emaS > emaM and emaM > emaL
above26_2days = close > emaL and close > emaL
baseTrendOK = (emaUpS and emaUpM and emaUpL) and goldenOrder and above26_2days
// =========================
// MACD
// =========================
= ta.macd(close, macdFast, macdSlow, macdSignal)
macdGC = ta.crossover(macdLine, macdSig)
macdUp = macdLine > macdLine
macdNearZero = math.abs(macdLine) <= macdZeroTh
macdGCAboveZero = macdGC and macdLine > 0 and macdSig > 0
macdMouOK = macdGC and macdNearZero and macdUp
macdBreakOK = allowMACDAboveZeroInstead ? (macdMouOK or macdGCAboveZero) : macdMouOK
// =========================
// Volume
// =========================
volMA = ta.sma(volume, volLookback)
volRatio = volMA > 0 ? (volume / volMA) : na
volumeMouOK = volRatio >= volMinRatio and volRatio <= volMaxRatio
volumeStrongOK = volRatio >= volStrong and volRatio <= volMaxRatio
// =========================
// Candle patterns
// =========================
body = math.abs(close - open)
upperWick = high - math.max(open, close)
lowerWick = math.min(open, close) - low
pinbar = (lowerWick >= wickBodyMult * body) and (lowerWick > upperWick) and (close >= open)
bullEngulf = close > open and close < open and close >= open and open <= close
bigBull = close > open and open < emaM and close > emaS and (body > ta.sma(body, 20))
candleOK = pinbar or bullEngulf or bigBull
// =========================
// Resistance / Pullback route
// =========================
res = ta.highest(high, pivotLen)
pullbackPct = res > 0 ? (res - close) / res * 100.0 : na
pullbackOK = pullbackPct >= pullMinPct and pullbackPct <= pullMaxPct
brokeRes = ta.crossover(close, res )
barsSinceBreak = ta.barssince(brokeRes)
afterBreakZone = (barsSinceBreak >= 0) and (barsSinceBreak <= breakLookbackBars)
pullbackRouteOK = afterBreakZone and pullbackOK
// =========================
// Breakout route (押し目なし初動ブレイク)
// =========================
breakConfirm = close > res * (1.0 + breakConfirmPct / 100.0)
bullBreak = close > open
bodyMA = ta.sma(body, bigBodyLookback)
bigBodyOK = bodyMA > 0 ? (body >= bodyMA * bigBodyMult) : false
rng = math.max(high - low, syminfo.mintick)
closeNearHighOK = not requireCloseNearHigh ? true : ((high - close) / rng * 100.0 <= closeNearHighPct)
mou_breakout = useBreakoutRoute and baseTrendOK and breakConfirm and bullBreak and bigBodyOK and closeNearHighOK and volumeStrongOK and macdBreakOK
mou_pullback = baseTrendOK and volumeMouOK and candleOK and macdMouOK and pullbackRouteOK
mou = mou_pullback or mou_breakout
// =========================
// KAKU (Strict): 8条件 + 最終三点
// =========================
cond1 = emaUpS and emaUpM and emaUpL
cond2 = goldenOrder
cond3 = above26_2days
cond4 = macdGCAboveZero
cond5 = volumeMouOK
cond6 = candleOK
cond7 = pullbackOK
cond8 = pullbackRouteOK
all8_strict = cond1 and cond2 and cond3 and cond4 and cond5 and cond6 and cond7 and cond8
final3 = pinbar and macdGCAboveZero and volumeStrongOK
kaku = all8_strict and final3
// =========================
// Entry (strategy)
// =========================
entrySignal = entryMode == "KAKU only" ? kaku : (mou or kaku)
canEnter = strategy.position_size == 0
newEntryKaku = canEnter and kaku and entrySignal
newEntryMouB = canEnter and (not kaku) and mou_breakout and entrySignal
newEntryMou = canEnter and (not kaku) and mou_pullback and entrySignal
// --- Publish Assist(保険エントリー) ---
// 条件が厳しすぎて「トレード0件」だと投稿時に警告が出る。
// closedtradesが0の間だけ、軽いEMAクロスで1回だけ拾う(その後は沈黙)。
assistFast = ta.ema(close, 5)
assistSlow = ta.ema(close, 20)
assistEntry = publishAssist and strategy.closedtrades == 0 and canEnter and ta.crossover(assistFast, assistSlow)
// 実エントリー
if newEntryKaku or newEntryMouB or newEntryMou or assistEntry
strategy.entry("LONG", strategy.long)
// ラベル(視認)
if showMouLabels and newEntryMou
label.new(bar_index, low, "猛(IN)", style=label.style_label_up, color=color.new(color.lime, 0), textcolor=color.black)
if showMouLabels and newEntryMouB
label.new(bar_index, low, "猛B(IN)", style=label.style_label_up, color=color.new(color.lime, 0), textcolor=color.black)
if showKakuLabels and newEntryKaku
label.new(bar_index, low, "確(IN)", style=label.style_label_up, color=color.new(color.yellow, 0), textcolor=color.black)
if assistEntry
label.new(bar_index, low, "ASSIST(IN)", style=label.style_label_up, color=color.new(color.aqua, 0), textcolor=color.black)
// =========================
// Exit (TP/SL + 強制クローズ)
// =========================
inPos = strategy.position_size > 0
tpPx = inPos ? strategy.position_avg_price * (1.0 + tpPct/100.0) : na
slPx = inPos ? strategy.position_avg_price * (1.0 - slPct/100.0) : na
if enableTPSL
strategy.exit("TP/SL", from_entry="LONG", limit=tpPx, stop=slPx)
// 最大保有バーで強制決済(これが「レポート無し」回避の最後の保険)
var int entryBar = na
if strategy.position_size > 0 and strategy.position_size == 0
entryBar := bar_index
if strategy.position_size == 0
entryBar := na
forceClose = inPos and not na(entryBar) and (bar_index - entryBar >= maxHoldBars)
if forceClose
strategy.close("LONG")
// =========================
// 利確/損切/強制クローズのラベル
// =========================
closedThisBar = (strategy.position_size > 0) and (strategy.position_size == 0)
avgPrev = strategy.position_avg_price
tpPrev = avgPrev * (1.0 + tpPct/100.0)
slPrev = avgPrev * (1.0 - slPct/100.0)
hitTP = closedThisBar and high >= tpPrev
hitSL = closedThisBar and low <= slPrev
// 同一足TP/SL両方は厳密に判断できないので、表示は「TP優先」で簡略(投稿ギリギリ版)
if hitTP
label.new(bar_index, high, "利確", style=label.style_label_down, color=color.new(color.lime, 0), textcolor=color.black)
else if hitSL
label.new(bar_index, low, "損切", style=label.style_label_up, color=color.new(color.red, 0), textcolor=color.white)
else if closedThisBar and forceClose
label.new(bar_index, close, "時間決済", style=label.style_label_left, color=color.new(color.gray, 0), textcolor=color.white)
// =========================
// Signals (猛/猛B/確)
// =========================
plotshape(showMouLabels and mou_pullback and not kaku, title="MOU_PULLBACK", style=shape.labelup, text="猛",
color=color.new(color.lime, 0), textcolor=color.black, location=lblLoc, size=size.tiny)
plotshape(showMouLabels and mou_breakout and not kaku, title="MOU_BREAKOUT", style=shape.labelup, text="猛B",
color=color.new(color.lime, 0), textcolor=color.black, location=lblLoc, size=size.tiny)
plotshape(showKakuLabels and kaku, title="KAKU", style=shape.labelup, text="確",
color=color.new(color.yellow, 0), textcolor=color.black, location=lblLoc, size=size.small)
// =========================
// Alerts
// =========================
alertcondition(mou, title="MNO_MOU", message="MNO: MOU triggered")
alertcondition(mou_breakout, title="MNO_MOU_BREAKOUT", message="MNO: MOU Breakout triggered")
alertcondition(mou_pullback, title="MNO_MOU_PULLBACK", message="MNO: MOU Pullback triggered")
alertcondition(kaku, title="MNO_KAKU", message="MNO: KAKU triggered")
alertcondition(assistEntry, title="MNO_ASSIST_ENTRY", message="MNO: ASSIST ENTRY (publish safety)")
// =========================
// Status label(最終足に必ず表示)
// =========================
var label status = na
if showStatusLbl and barstate.islast
label.delete(status)
statusTxt =
"MNO RUNNING\n" +
"ClosedTrades: " + str.tostring(strategy.closedtrades) + "\n" +
"BaseTrend: " + (baseTrendOK ? "OK" : "NO") + "\n" +
"MOU: " + (mou ? "YES" : "no") + " (猛=" + (mou_pullback ? "Y" : "n") + " / 猛B=" + (mou_breakout ? "Y" : "n") + ")\n" +
"KAKU: " + (kaku ? "YES" : "no") + "\n" +
"VolRatio: " + (na(volRatio) ? "na" : str.tostring(volRatio, format.mintick)) + "\n" +
"Pull%: " + (na(pullbackPct) ? "na" : str.tostring(pullbackPct, format.mintick)) + "\n" +
"Pos: " + (inPos ? "IN" : "OUT")
status := label.new(bar_index, high, statusTxt, style=label.style_label_left, textcolor=color.white, color=color.new(color.black, 0))
// =========================
// Debug table(最終足のみ)
// =========================
var table t = table.new(position.top_right, 2, 14, border_width=1, border_color=color.new(color.white, 60))
fRow(_name, _cond, _r) =>
bg = _cond ? color.new(color.lime, 70) : color.new(color.red, 80)
tx = _cond ? "OK" : "NO"
table.cell(t, 0, _r, _name, text_color=color.white, bgcolor=color.new(color.black, 0))
table.cell(t, 1, _r, tx, text_color=color.white, bgcolor=bg)
if showDebugTbl and barstate.islast
table.cell(t, 0, 0, "MNO Debug", text_color=color.white, bgcolor=color.new(color.black, 0))
table.cell(t, 1, 0, "", text_color=color.white, bgcolor=color.new(color.black, 0))
fRow("BaseTrend", baseTrendOK, 1)
fRow("MOU Pullback", mou_pullback, 2)
fRow("MOU Breakout", mou_breakout, 3)
fRow("Break confirm", breakConfirm, 4)
fRow("Break big body", bigBodyOK, 5)
fRow("Break close high", closeNearHighOK, 6)
fRow("Break vol strong", volumeStrongOK, 7)
fRow("Break MACD", macdBreakOK, 8)
fRow("KAKU all8", all8_strict, 9)
fRow("KAKU final3", final3, 10)
fRow("AssistEntry", assistEntry, 11)
fRow("ClosedTrades>0", strategy.closedtrades > 0, 12)






















